﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using W.Purchase.API.Application.Command.ReceivableCommand;
using W.Purchase.Domain;
using W.Purchase.Repository.Interface;

namespace W.Purchase.API.Application.CommandHandler.ReceivableCommandHandler
{
    public class ActualpaymentCommandHandler:IRequestHandler<ActualpaymentCreateCommand,int>
    {
        private readonly IReceivableRepository _receivableRepository;
        private readonly IActualpaymentRepository _actualpaymentRepository;
        private readonly IMapper _mapper;
        public ActualpaymentCommandHandler(IReceivableRepository receivableRepository, IActualpaymentRepository actualpaymentRepository)
        {
            _receivableRepository = receivableRepository;
            _actualpaymentRepository = actualpaymentRepository;
        }

        public async Task<int> Handle(ActualpaymentCreateCommand request, CancellationToken cancellationToken)
        {
            using (var tran = _actualpaymentRepository.DB.Database.BeginTransaction(System.Data.IsolationLevel.Serializable))
            {
                try
                {
                    #region 实收信息表添加数据
                    Actualpayment actualpayment=new Actualpayment();
                    actualpayment.ReceivableSerialNumber=request.ReceivableSerialNumber;
                    actualpayment.PayerDepartment = request.PayerDepartment;
                    actualpayment.FinanceTypeName = request.FinanceTypeName;
                    actualpayment.EndDate = request.EndDate;
                    actualpayment.PayMoney = request.PayMoney;
                    actualpayment.Actualpaymentremark = request.Actualpaymentremark;
                    await _actualpaymentRepository.AddAsync(actualpayment);
                    #endregion

                    #region 修改应收表数据
                    var list = await _receivableRepository.GetAllAsaync();
                    var plist=list.Where(c=>c.ReceivableSerialNumber==actualpayment.ReceivableSerialNumber).FirstOrDefault();
                    if (plist != null)
                    {
                        plist.ReceivableId = plist.ReceivableId;
                        plist.PracticalMoey += actualpayment.PayMoney;
                        plist.ResidueMoney = plist.ReceivableMoney - actualpayment.PayMoney;
                        await _receivableRepository.Update(plist);
                    }
                    #endregion
                    var code = await _actualpaymentRepository.DB.SaveChangesAsync();
                    tran.Commit();
                    return code;
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    return 1;
                }
            }
        }
    }
}
